package org.lib.eshello.news.service.impl;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.lib.eshello.news.dao.NewsDAO;
import org.lib.eshello.news.dto.AddNewsDTO;
import org.lib.eshello.news.dto.FindByPageDTO;
import org.lib.eshello.news.entity.News;
import org.lib.eshello.news.service.NewsService;
import org.lib.eshello.news.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.util.Streamable;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * NewsService实现类
 * @author ben
 * @date 2021-09-17 10:07:00 CST
 */
@Service
@Slf4j
public class NewsServiceImpl implements NewsService {

	@Autowired
	private NewsDAO newsDao;

	@Override
	public String addNews(AddNewsDTO dto) {
		News news = dto.convertToNews();
		News savedNews = newsDao.save(news);
		log.info("添加新闻：id={}", savedNews.getId());
		return savedNews.getId();
	}

	@Override
	public List<News> getAll() {
		List<News> ret = new ArrayList<News>(20);
		
		Iterable<News> iter = newsDao.findAll();
		iter.forEach(item -> {
			ret.add(item);
		});
		
		return ret;
	}

	@Override
	public News getById(String id) {
		return newsDao.findById(id).orElse(null);
	}

	@Override
	public List<News> findByTitle(String title) {
		return newsDao.findByTitle(title);
	}

	@Override
	public List<News> findByTitleContaining(String title) {
		List<News> ret = new LinkedList<>();
		
		Streamable<News> stream = newsDao.findByTitleContaining(title);
		stream.forEach(item -> {
			ret.add(item);
		});
		 
		log.info("findByTitleContaining ret.size={}", ret.size());
		return ret;
	}

	@Override
	public PageVO<News> findByTitleOrContentText(FindByPageDTO dto) {
		PageVO<News> page = new PageVO<News>();
		page.setPageNo(dto.getPageNo());
		page.setPageSize(dto.getPageSize());
		
//		Pageable pageable = PageRequest.of(dto.getPageNo(), dto.getPageSize());
		// 排序：按照 postTime 倒序返回
		Pageable pageable = PageRequest.of(dto.getPageNo(), dto.getPageSize(), Sort.by(Direction.DESC, "postTime"));
		// 方式1：单个汉字，查询结果不全
		Page<News> daoPage = newsDao.findByTitleOrContentText(dto.getKeyword(), dto.getKeyword(), pageable);
		// 方式2：单个汉字，可以查到符合要求的所有
//		Page<News> daoPage = newsDao.findByTitleContainingOrContentTextContaining(dto.getKeyword(), dto.getKeyword(), pageable);
		
		log.info("daoPage={}", daoPage);
		page.setTotalPage(daoPage.getTotalPages());
		page.setTotalSize(daoPage.getTotalElements());
		// 内容
		page.setData(daoPage.getContent());
		
		return page;
	}

	@Override
	public boolean deleteById(String id) {
		log.info("删除News: id={}", id);
		newsDao.deleteById(id);
		return newsDao.existsById(id);
	}
	
}
